package com.xxxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxy.dao.*;
import com.xxxy.model.*;
import com.xxxy.redis.service.RedisService;
import com.xxxy.response.*;
import com.xxxy.service.TeacherReviewedService;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author StevenShen
 * @date 2022/3/12 11:45
 */
@Service
public class TeacherReviewedServiceImpl extends ServiceImpl<TeacherReviewedDao, TeacherReviewed> implements TeacherReviewedService {

    @Autowired
    private TeacherReviewedDao teacherReviewedDao;

    @Autowired
    private ReviewedDao reviewedDao;

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private StudentAnswerDao studentAnswerDao;

    @Autowired
    private ExamplePaperDao examplePaperDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ExaminationPaperDao examinationPaperDao;

    @Override
    public List<ReviewedPaperListResponse> getReviewedList(String teacherAccount) {
        return teacherReviewedDao.getReviewedList(teacherAccount);
    }

    @Override
    public ExamplePaperTeacherResponse getExampleQuestion(Integer examinationPaperId, Integer questionIndex) {

        // 单个试题
        ExamplePaperTeacherResponse paperResponse = new ExamplePaperTeacherResponse();
        paperResponse.setPaperId(examinationPaperId);
        paperResponse.setQuestionIndex(questionIndex);

        // 获取试题内容和参考答案
        QueryWrapper<Reviewed> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("paper_id", examinationPaperId);
        wrapper1.eq("question_index", questionIndex);
        Reviewed reviewed = reviewedDao.selectOne(wrapper1);
        Question question = questionDao.selectById(reviewed.getQuestionId());
        paperResponse.setQuestionContent(question.getContent());
        paperResponse.setReferenceAnswer(question.getAnswer());

        // 获取学生答案和编号
        List<ExampleQuestionTeacherResponse> list1 = new ArrayList<>();
        ExampleQuestionTeacherResponse questionResponse = null;

        QueryWrapper<StudentAnswer> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("examination_paper_id", examinationPaperId);
        wrapper2.eq("is_example", 1);
        List<StudentAnswer> studentAnswers = studentAnswerDao.selectList(wrapper2);
        for (int j = 0; j < studentAnswers.size(); j++) {
            questionResponse = new ExampleQuestionTeacherResponse();

            String answerSituation = studentAnswers.get(j).getAnswerSituation();
            String scoreSituation = studentAnswers.get(j).getScoreSituation();

            String[] answers = answerSituation.split(",");
            String[] scores = scoreSituation.split(",");

            questionResponse.setStudentAnswerId(studentAnswers.get(j).getId());
            questionResponse.setStudentAnswer(answers[questionIndex]);
            questionResponse.setScore(scores[questionIndex]);

            list1.add(questionResponse);
        }
        paperResponse.setStudentAnswers(list1);

        // 获取允许误差
        QueryWrapper<ExamplePaper> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("paper_id", examinationPaperId);
        ExamplePaper examplePaper = examplePaperDao.selectOne(wrapper3);
        paperResponse.setAllowableError(examplePaper.getAllowableError());

        return paperResponse;
    }

    @Override
    public ReviewedQuestionResponse getReviewedQuestion(Integer examinationPaperId, Integer questionIndex) {

        ReviewedQuestionResponse questionResponse = new ReviewedQuestionResponse();

        questionResponse.setPaperId(examinationPaperId);
        questionResponse.setQuestionIndex(questionIndex);

        QueryWrapper<Reviewed> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", examinationPaperId);
        wrapper.eq("question_index", questionIndex);
        Reviewed reviewed = reviewedDao.selectOne(wrapper);
        questionResponse.setFullScore(reviewed.getFullScore());

        // 查询试题内容和参考答案
        Integer questionId = reviewed.getQuestionId();
        Question question = questionDao.selectById(questionId);
        String content = question.getContent();
        String answer = question.getAnswer();

        questionResponse.setQuestionContent(content);
        questionResponse.setReferenceAnswer(answer);

        // 查询编号和学生答案
        String reviewedStudent = reviewed.getReviewedStudent();
        String studentStatus = reviewed.getStudentStatus();

        String[] reviewedStudents = reviewedStudent.split(",");
        String[] studentStatuses = studentStatus.split(",");

        Integer number = null;
        for (int i = 0; i < studentStatuses.length; i++) {
            if ("0".equals(studentStatuses[i])) {
                number = Integer.valueOf(reviewedStudents[i]);
                questionResponse.setReviewedId(number);
                // 将status设为1
                studentStatuses[i] = "1";
                break;
            }
        }
        if (number == null) {
            ExaminationPaper examinationPaper = examinationPaperDao.selectById(examinationPaperId);
            // 设置试卷status=6
            examinationPaper.setStatus(6);
            examinationPaperDao.updateById(examinationPaper);
            return null;
        }

        // 更新reviewed
        reviewed.setStudentStatus(StringUtils.join(Arrays.asList(studentStatuses), ','));
        reviewedDao.updateById(reviewed);

        StudentAnswer studentAnswers = studentAnswerDao.selectById(number);
        String answerSituation = studentAnswers.getAnswerSituation();
        String[] answers = answerSituation.split(",");
        String studentAnswer = answers[questionIndex];

        questionResponse.setStudentAnswer(studentAnswer);

        return questionResponse;
    }

    @Override
    public Boolean setScore(Integer reviewedId, Integer questionIndex, Double score, String teacherAccount) {

        StudentAnswer studentAnswer = studentAnswerDao.selectById(reviewedId);
        String scoreSituation = studentAnswer.getScoreSituation();
        String[] scores = scoreSituation.split(",");
        scores[questionIndex] = score.toString();
        studentAnswer.setScoreSituation(StringUtils.join(Arrays.asList(scores), ','));
        Double totalScore = studentAnswer.getTotalScore();
        totalScore += score;
        studentAnswer.setTotalScore(totalScore);

        // 教师已批阅题数+1
        Integer paperId = studentAnswer.getExaminationPaperId();
        QueryWrapper<TeacherReviewed> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", paperId);
        wrapper.eq("question_index", questionIndex);
        wrapper.eq("teacher_account", teacherAccount);
        TeacherReviewed teacherReviewed = teacherReviewedDao.selectOne(wrapper);
        Integer reviewedNumber = teacherReviewed.getReviewedNumber();
        teacherReviewed.setReviewedNumber(reviewedNumber + 1);

        return studentAnswerDao.updateById(studentAnswer) == 1 && teacherReviewedDao.updateById(teacherReviewed) == 1;
    }

    @Override
    public List<TeacherProgressResponse> getTeacherProgress(Integer examinationPaperId, Integer questionIndex) {

        // 获取该试卷的进度信息
        List<ReviewedServiceImpl.ReviewedQuestionProgress> progressList = (List<ReviewedServiceImpl.ReviewedQuestionProgress>) redisService.get(String.valueOf(examinationPaperId));

        // 获取每个教师的进度
        List<ReviewedServiceImpl.TeacherProgress> teacherProgressList = new ArrayList<>();
        for (int i = 0; i < progressList.size(); i++) {
            ReviewedServiceImpl.ReviewedQuestionProgress questionProgress = progressList.get(i);
            if (questionProgress.getQuestionIndex().equals(questionIndex)) {
                teacherProgressList = questionProgress.getTeacherProgressList();
                break;
            }
        }

        QueryWrapper<TeacherReviewed> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", examinationPaperId);
        wrapper.eq("question_index", questionIndex);
        List<TeacherReviewed> teacherReviewedList = teacherReviewedDao.selectList(wrapper);

        List<TeacherProgressResponse> list = new ArrayList<>();
        for (int i = 0; i < teacherReviewedList.size(); i++) {
            // 已批阅份数
            Integer reviewedNumber = teacherReviewedList.get(i).getReviewedNumber();
            // 查询教师账号和姓名
            String teacherAccount = teacherReviewedList.get(i).getTeacherAccount();
            String teacherName = teacherReviewedDao.getTeacher(teacherAccount);
            // 获取教师阅卷速度
            int speed = 0;
            // 教师每小时批阅总份数
            List<Integer> reviewedTotalPerHour = new ArrayList<>();
            // 教师每小时批阅份数
            List<Integer> reviewedPerHour = new ArrayList<>();
            for (int j = 0; j < teacherProgressList.size(); j++) {
                ReviewedServiceImpl.TeacherProgress teacherProgress = teacherProgressList.get(j);
                if (teacherProgress.getTeacherAccount().equals(teacherAccount)) {
                    List<Integer> teacherReviewedNumber = teacherProgress.getTeacherReviewedNumber();
                    Integer nowNumber = teacherReviewedNumber.get(teacherReviewedNumber.size() - 1);
                    Integer lastNumber = teacherReviewedNumber.get(teacherReviewedNumber.size() - 2);
                    int number = nowNumber - lastNumber;
                    speed = number;

                    // 教师每小时批阅总份数
                    for (int k = 0; k < teacherReviewedNumber.size(); k++) {
                        reviewedTotalPerHour.add(teacherReviewedNumber.get(k));
                        if (k == 0) {
                            reviewedPerHour.add(teacherReviewedNumber.get(0));
                        } else {
                            reviewedPerHour.add(teacherReviewedNumber.get(k) - teacherReviewedNumber.get(k - 1));
                        }
                    }
                    break;
                }
            }

            TeacherProgressResponse teacherProgressResponse = new TeacherProgressResponse();
            teacherProgressResponse.setPaperId(examinationPaperId);
            teacherProgressResponse.setQuestionIndex(questionIndex);
            teacherProgressResponse.setTeacherAccount(teacherAccount);
            teacherProgressResponse.setTeacherName(teacherName);
            teacherProgressResponse.setSpeed(speed);
            teacherProgressResponse.setReviewedNumber(reviewedNumber);
            teacherProgressResponse.setReviewedTotalPerHour(reviewedTotalPerHour);
            teacherProgressResponse.setReviewedPerHour(reviewedPerHour);

            list.add(teacherProgressResponse);
        }

        return list;
    }

    @Override
    public TeacherPaperProgressResponse getPaperProgress(Integer examinationPaperId, String teacherAccount) {

        // 获取该教师批阅的试题
        QueryWrapper<TeacherReviewed> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", examinationPaperId);
        wrapper.eq("teacher_account", teacherAccount);
        List<TeacherReviewed> teacherReviewedList = teacherReviewedDao.selectList(wrapper);

        // 该教师批阅题目的题号列表
        List<Integer> questionIndexList = new ArrayList<>();
        for (int i = 0; i < teacherReviewedList.size(); i++) {
            Integer questionIndex = teacherReviewedList.get(i).getQuestionIndex();
            questionIndexList.add(questionIndex);
        }

        TeacherPaperProgressResponse teacherPaperProgressResponse = new TeacherPaperProgressResponse();
        teacherPaperProgressResponse.setPaperId(examinationPaperId);

        List<TeacherQuestionProgressResponse> teacherQuestionProgressResponseList = new ArrayList<>();
        TeacherQuestionProgressResponse teacherQuestionProgressResponse = null;

        // 获取该试卷的进度信息
        List<ReviewedServiceImpl.ReviewedQuestionProgress> progressList = (List<ReviewedServiceImpl.ReviewedQuestionProgress>) redisService.get(String.valueOf(examinationPaperId));

        // 该教师批阅的所有试题的总批阅量
        List<Integer> totalProgress = new ArrayList<>();

        // 获取每道题的进度
        for (int i = 0; i < progressList.size(); i++) {
            teacherQuestionProgressResponse = new TeacherQuestionProgressResponse();

            // 题号
            Integer questionIndex = progressList.get(i).getQuestionIndex();
            teacherQuestionProgressResponse.setQuestionIndex(questionIndex);
            if (questionIndexList.contains(questionIndex)) {
                // 该题每小时累计批阅量
                List<Integer> reviewedNumber = progressList.get(i).getReviewedNumber();
                addIntegerList(totalProgress, reviewedNumber);
                teacherQuestionProgressResponse.setQuestionProgress(reviewedNumber);
                teacherQuestionProgressResponseList.add(teacherQuestionProgressResponse);
            }

        }

        teacherPaperProgressResponse.setTotalProgress(totalProgress);
        teacherPaperProgressResponse.setQuestionProgressList(teacherQuestionProgressResponseList);

        return teacherPaperProgressResponse;
    }

    @Override
    public ReviewedPaperProgressResponse getQuestionProgress(Integer examinationPaperId, String teacherAccount) {
        // 获取该试卷的进度信息
        List<ReviewedServiceImpl.ReviewedQuestionProgress> list = (List<ReviewedServiceImpl.ReviewedQuestionProgress>) redisService.get(String.valueOf(examinationPaperId));

        // 阅卷进度
        Double reviewedProgress = null;
        // 阅卷速度（题每小时）
        Long reviewedSpeed = null;
        // 预计完成时间
        Date estimatedTime = null;
        // 阅卷进度和
        double totalProgress = 0;
        // 最晚预计完成时间
        Date latestTime = new Date();

        // 获取该教师批阅试题的题号列表
        QueryWrapper<TeacherReviewed> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("paper_id", examinationPaperId);
        wrapper1.eq("teacher_account", teacherAccount);
        List<TeacherReviewed> teacherReviewedList = teacherReviewedDao.selectList(wrapper1);
        List<Integer> questionIndexList = new ArrayList<>();
        for (int i = 0; i < teacherReviewedList.size(); i++) {
            Integer questionIndex = teacherReviewedList.get(i).getQuestionIndex();
            questionIndexList.add(questionIndex);
        }

        // 获取该教师批阅试题的进度
        List<ReviewedQuestionProgressResponse> reviewedQuestionProgressList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            ReviewedServiceImpl.ReviewedQuestionProgress reviewedQuestionProgress = list.get(i);
            if (questionIndexList.contains(reviewedQuestionProgress.getQuestionIndex())) {
                // 获取试题总份数
                Integer questionIndex = reviewedQuestionProgress.getQuestionIndex();
                QueryWrapper<Reviewed> wrapper = new QueryWrapper<>();
                wrapper.eq("paper_id", examinationPaperId);
                wrapper.eq("question_index", questionIndex);
                Reviewed reviewed = reviewedDao.selectOne(wrapper);
                String studentStatus = reviewed.getStudentStatus();
                String[] status = studentStatus.split(",");
                // 计算试题的进度
                List<Integer> reviewedNumber = reviewedQuestionProgress.getReviewedNumber();
                Integer nowNumber = reviewedNumber.get(reviewedNumber.size() - 1);
                // 阅卷进度
                reviewedProgress = 1.0 * nowNumber / status.length;
                totalProgress += reviewedProgress;
                // 阅卷速度（题每小时）
                Integer lastNumber = reviewedNumber.get(reviewedNumber.size() - 2);
                reviewedSpeed = (long) (nowNumber - lastNumber);
                // 预计完成时间
                if (reviewedSpeed == 0) {
                    estimatedTime = new Date(System.currentTimeMillis()
                            + (long) (status.length - nowNumber) * 60 * 60 * 1000);
                } else {
                    estimatedTime = new Date(System.currentTimeMillis()
                            + (long) ((status.length - nowNumber) / reviewedSpeed * 60 * 60 * 1000));
                }
                // 最晚预计完成时间
                if (estimatedTime.after(latestTime)) {
                    latestTime = estimatedTime;
                }

                ReviewedQuestionProgressResponse questionProgressResponse = new ReviewedQuestionProgressResponse();
                questionProgressResponse.setQuestionIndex(questionIndex);
                questionProgressResponse.setReviewedProgress(reviewedProgress);
                questionProgressResponse.setEstimatedTime(estimatedTime);
                questionProgressResponse.setQuestionId(reviewed.getQuestionId());
                reviewedQuestionProgressList.add(questionProgressResponse);
            }

        }

        ReviewedPaperProgressResponse response = new ReviewedPaperProgressResponse();
        response.setPaperId(examinationPaperId);
        // 阅卷总进度
        response.setReviewedProgress(totalProgress / list.size());
        response.setEstimatedTime(latestTime);
        response.setReviewedQuestionProgressList(reviewedQuestionProgressList);

        return response;
    }

    @Override
    public List<ReviewedQuestionListResponse> getQuestionList(Integer examinationPaperId, String teacherAccount) {
        List<ReviewedQuestionListResponse> questionList = new ArrayList<>();
        ReviewedQuestionListResponse question = null;

        QueryWrapper<TeacherReviewed> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_id", examinationPaperId);
        wrapper.eq("teacher_account", teacherAccount);
        List<TeacherReviewed> teacherReviewedList = teacherReviewedDao.selectList(wrapper);
        for (int i = 0; i < teacherReviewedList.size(); i++) {
            TeacherReviewed teacherReviewed = teacherReviewedList.get(i);
            question = new ReviewedQuestionListResponse();
            Integer questionIndex = teacherReviewed.getQuestionIndex();
            question.setQuestionIndex(questionIndex);
            // 查询教师姓名
            List<String> teachers = teacherReviewedDao.getTeachers(examinationPaperId, questionIndex);
            question.setTeachers(teachers);
            question.setPassExample(teacherReviewed.getPassExample());
            // 查询该题的分值
            QueryWrapper<Reviewed> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("paper_id", examinationPaperId);
            wrapper1.eq("question_index", teacherReviewed.getQuestionIndex());
            Reviewed reviewed = reviewedDao.selectOne(wrapper1);
            question.setFullScore(reviewed.getFullScore());
            question.setQuestionId(reviewed.getQuestionId());
            questionList.add(question);
        }

        return questionList;
    }

    /**
     * 数字列表相加
     */
    private void addIntegerList(List<Integer> totalProgress, List<Integer> reviewedNumber) {
        if (totalProgress.isEmpty()) {
            totalProgress.addAll(reviewedNumber);
        } else {
            for (int i = 0; i < totalProgress.size(); i++) {
                totalProgress.set(i, totalProgress.get(i) + reviewedNumber.get(i));
            }
        }
    }

}